/**
 * @author 扫地僧 (saods@ebidding.com.cn)
 * @version 1.0
 * @date 2018/6/7 10:48
 * @since 1.0
 */

var $list = $('#thelist'),
    // $btn = $('#ctlBtn'),
    state = 'pending';
var uploader = WebUploader.create({

    // swf文件路径
    swf: '/assets/js/webuploader/Uploader.swf',

    // 文件接收服务端。
    server: '/api/uploadAttachment',

    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: '#picker',

    // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
    resize: false,
    auto:true,
    formData:{
        isAttachment: true
    },
    fileNumLimit:3
});
// 当有文件被添加进队列的时候
uploader.on( 'fileQueued', function( file ) {
    // var $list = $('#thelist');
    var fileDes = '<div id="' + file.id + '" class="item">' +
        '<h4 class="info">' + file.name + '</h4>' +
        '<a id="delete-file" class="state" onclick="deleteFileFromList(this)">删除</a>';
    if(file.source.id){
        fileDes += '<input id="file-'+file.source.id+'" type="hidden" name="fileIds" value="'+file.source.id+'"/>';
    }

    fileDes += '</div>';
    $list.append(fileDes);
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
    var $li = $( '#'+file.id ),
        $percent = $li.find('.progress .progress-bar');

    // 避免重复创建
    if ( !$percent.length ) {
        $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
    }

    $li.find('a.state').text('上传中');

    $percent.css( 'width', percentage * 100 + '%' );
});
uploader.on( 'uploadSuccess', function( file ,response) {

    $( '#'+file.id ).find('a.state').text('删除');
    var fileId = response.fileIdArray[0];

    $( '#'+file.id ).find('a.state').after('<input id="file-'+ fileId +'" type="hidden" name="fileIds" value="'+ fileId +'"/>');
    console.log( uploader.getFiles() );
});


uploader.on( 'uploadError', function( file ) {
    $( '#'+file.id ).find('a.state').text('上传出错');
});

uploader.on( 'uploadComplete', function( file ) {
    $( '#'+file.id ).find('.progress').fadeOut();
});
function deleteFileFromList(obj) {
    var $item= $(obj).parent();
    var fileId = $item.attr('id');
    uploader.removeFile(fileId,true);
    $item.remove();

    // console.log(uploader.getFiles());
    // uploader.removeFile($(obj).parent().attr('id'),true);
    // console.log($(obj).next().remove());

}




// $("#input-id").fileinput({
//     'theme': 'explorer-fas',
//     'uploadUrl': '/api/uploadFileForMd',
//     uploadExtraData: {
//         isAttachment: true
//     },
//     browseClass: 'btn btn-success',
//     language: 'zh',
//     maxFileCount: 3,//可上传的最大文件数
//     showPreview: true,//
//     overwriteInitial: false,//是否覆盖掉initial预览的文件
//     // initialPreviewCount:4,
//     validateInitialCount: true,//maxFileCount是否包含初始化的文件数
//     msgFilesTooMany: "单篇文章最多允许上传3个附件！",
//     removeFromPreviewOnError: true,
//     initialPreviewAsData: true,
//     initialPreview:
//         // [
//         //     "1",
//         //     "2",
//         //     "3"
//         // ]
//         [
//         "http://lorempixel.com/1920/1080/nature/1",
//         "http://lorempixel.com/1920/1080/nature/2",
//         "http://lorempixel.com/1920/1080/nature/3"
//     ]
//     ,
//     initialPreviewConfig: [
//         {caption: "nature-1.jpg",  url: "{$url}", key: 1},
//         {caption: "nature-2.jpg", url: "{$url}", key: 20},
//         {caption: "nature-3.jpg",  url: "{$url}", key: 3}
//     ],
//     fileActionSettings: {
//         showRemove: true,
//         showDrag: false
//     },
//     hideThumbnailContent: false,
//     showRemove: false
// }).on('filedeleted', function (event, id, index) {
//     console.log('id = ' + id + ', index = ' + index);
// }).on('fileremoved', function (event, id, index) {
//     console.log('id = ' + id + ', index = ' + index);
// }).on('fileuploaded', function (event, data, previewId, index) {
//     // var form = data.form, files = data.files, extra = data.extra,
//     //     response = data.response, reader = data.reader;
//     var fileId = data.response.fileIdArray[0];
//     var fileIdsStr = $('#article-fileIds').val();
//     if (fileIdsStr != '') {
//         var fileIdArr = fileIdsStr.split(',');
//     } else {
//         var fileIdArr = [];
//     }
//
//     addIfNoExist(fileIdArr, fileId);
//     fileIdsStr = fileIdArr.join(',');
//     $('#article-fileIds').val(fileIdsStr);
//
//     $('#' + previewId).find('.kv-file-remove').attr('data-key', fileId);
//
//     function addIfNoExist(arr, id) {
//         for (var item in arr) {
//             if (item == id) {
//                 break;
//             }
//         }
//         arr.push(id);
//         arr.sort();
//     }
// });


// });

var $publishForm = $("#publishForm");
if (articleId) {
    setTimeout(function () {
        $.ajax({
            type: "post",
            url: "/article/get/" + articleId,
            success: function (json) {

                $.alert.ajaxSuccess(json);
                var info = json.data;

                // 标签, 因为标签初始化是有延迟的，所以这而赋值的时候为了防止赋值失败，亦采用延迟处理
                setTimeout(function () {
                    var tags = info.tags;
                    for (var i = 0, len = tags.length; i < len; i++) {
                        var tag = tags[i];
                        $('input[target="tagsinput"]').tagsinput('add', {"id": tag.id, "name": tag.name}, {add: false});
                    }
                }, 600);
                if ($('input[name=original]')) {
                    $('input[name=original]').iCheck(info.original ? 'check' : 'uncheck');
                }
                if ($('#comment')) {
                    $('#comment').iCheck(info.comment ? 'check' : 'uncheck');
                }
                if (info['coverImage']) {
                    $(".coverImage").attr('src', info['coverImage']);
                }
                var contentMd = info['contentMd'];
                if (contentMd) {
                    $("#contentMd").val(contentMd);
                    if (simplemde) {
                        simplemde.value(contentMd);
                    }
                }
                var contentHtml = info['content'];
                if (contentHtml) {
                    $("#content").val(contentHtml);
                    if (editor) {
                        editor.txt.html(contentHtml);
                    }
                }
                $publishForm.find("input[type!=checkbox], select, textarea").each(function () {
                    clearText($(this), this.type, info);
                });
                getGroupsTree($("#selectEditGroup"), 1, false);

                getGroupsTree($("#selectViewGroup"), 2, false);

                //初始化编辑页面文件
                var fileList = json.data.files;
                // fileList = [{originalFileName:'1.txt',id:'77'},{originalFileName:'2.docx',id:'88'}];
                if(fileList.length>0){
                    var files=[];
                    fileList.forEach(function (value , index ) {
                        var f = new WebUploader.File({
                            name:value.originalFileName,
                            id:value.id,
                            lastModifiedDate:value.uploadEndTime,
                            ext:value.originalFileName.substr(1),
                            size:value.size,
                        });
                        f.setStatus('complete');
                        files.push(f);

                    });
                    uploader.addFiles(files);
                    // console.log(uploader.getFiles());
                }
            },
            error: $.alert.ajaxError
        });

    }, 1000);
}

$(".to-choose-info").click(function () {
    if (validator.checkAll($publishForm)) {
        $("#publishModal").modal('show');

        $(".bootstrap-tagsinput input").keyup(function (event) {
            clearTagMatch();
            initTagMatchStyle();
            if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) {
                var search_value = $(".bootstrap-tagsinput input").val();
                tagArr.sort();
                if ($(".bootstrap-tagsinput input").val().replace(/(^\s*)|(\s*$)/g, '') == "") {
                    return;
                }//值为空，退出

                try {
                    var reg = new RegExp("(" + search_value + ")", "i");
                }

                catch (e) {
                    return;
                }

                var div_index = 0;//记录创建的DIV的索引

                for (var i = 0; i < tagArr.length; i++) {
                    if ($('#keyword-match').children().length > 9) {
                        break;
                    }

                    if (reg.test(tagArr[i].name)) {

                        var div = document.createElement("li");

                        div.className = "auto_onmouseout";
                        $(div).addClass('list-group-item');

                        div.seq = tagArr[i].name;

                        div.value = tagArr[i].id;

                        div.onclick = addTagByMatch(div);

                        // div.onmouseover=this.autoOnmouseover(this,div_index);

                        div.innerHTML = tagArr[i].name.replace(reg, "<strong>$1</strong>");//搜索到的字符粗体显示

                        $('#keyword-match').append(div);
                        $('#keyword-match').attr('class', 'auto_show');
                        div_index++;

                    }

                }

            }

            //TODO 绑定键位添加标签
            // this.pressKey(event);
            //初始化智能提示列表的样式
            function initTagMatchStyle() {
                // this.autoObj.style.left = this.obj.offsetLeft + "px";
                //
                // this.autoObj.style.top  = this.obj.offsetTop + this.obj.offsetHeight + "px";
                //
                // this.autoObj.style.width= this.obj.offsetWidth - 2 + "px";//减去边框的长度2px
            }

            function clearTagMatch() {
                $('#keyword-match').empty();
            }

            function addTagByMatch(div) {
                return function () {
                    //添加标签
                    var thisId = $(div).attr("value");
                    var thisText = $(div).text().trim();
                    $('input[target="tagsinput"]').tagsinput('add', {"id": thisId, "name": thisText}, {add: false});
                    //隐藏标签提示列
                    $('#keyword-match').attr('class', 'auto_hide');
                    $(".bootstrap-tagsinput input").val('');
                }
            }


        });
    }

});

$("#selectEditGroup").click(function () {
    console.log("选择编辑用户");
    var $this = $(this);
    getGroupsTree($this,1,true);
});


$("#selectViewGroup").click(function () {
    console.log("选择查看用户");
    var $this = $(this);
    getGroupsTree($this,2,true);
});


function getGroupsTree($this,authType,isClick){
    $.ajax({
        async: false,
        type: "POST",
        data: {articleId:articleId, authType:authType},
        url: '/groups/groupsListWithSelected',
        dataType: 'json',
        success: function (json) {
            var data = json.data;
            console.log(data);
            if(data != null && data != undefined){
                var id = new Array();
                var name = new Array();
                for(var i = 0 ; i < data.length ; i ++){
                    if(data[i].checked){
                        id.push(data[i].id);
                        name.push(data[i].name);
                    }
                }
                $this.val(name.join());
                $this.next("input").val(id.join());
            }
            if(isClick) {
                var setting = {
                    check: {
                        enable: true,
                        chkboxType: {"Y": "ps", "N": "ps"},
                        chkStyle: "checkbox"
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            console.log(treeNode.tId + ", " + treeNode.name + "," + treeNode.checked);
                            var treeObj = $.fn.zTree.getZTreeObj(treeId);
                            var nodes = treeObj.getCheckedNodes(true);
                            var ids = new Array();
                            var names = new Array();
                            for (var i = 0; i < nodes.length; i++) {
                                //获取选中节点的值
                                ids.push(nodes[i].id);
                                names.push(nodes[i].name);
                            }
                            $this.val(names.join());
                            $this.next("input").val(ids.join());
                            console.log(ids);
                            /*$.post(options.saveRolesUrl, {"userId": userId, "roleIds": ids.join(",")}, function (obj) {
                            }, 'json');*/
                        }
                    }
                };
                var tree = $.fn.zTree.init($("#treeDemo"), setting, data);
                tree.expandAll(true);//全部展开
                $('#selectGroup').modal('show');
            }
        }
    });
}


// 点击保存
$(".publishBtn").click(function () {
    if (validator.checkAll($publishForm)) {
        if (!$publishForm.find("input[name='tags']").val()) {
            $.alert.error("请至少选择一个标签");
            return;
        }
        if(!$("#editGroupIds").val()){
            $.alert.error("请选择可编辑组！");
            return;
        }
        if (!$("#description").val() || !$("#keywords").val()) {
            $.alert.error("请填写文章简介相关的内容，填写后更容易被点击和找到哦");
            return;
        }

        var isMarkdown = $("input[name=isMarkdown]").val();
        if (isMarkdown == 1 || isMarkdown == 'true') {
            $("#contentMd").val(simplemde.value());
            $("#content").val(simplemde.markdown(simplemde.value()));
        }

        $publishForm.ajaxSubmit({
            type: "post",
            url: "/article/save",
            success: function (json) {
                if (isMarkdown == 1) {
                    $.tool.delCache("smde_" + op.uniqueId);
                }
                $.alert.ajaxSuccess(json, function () {
                    window.location.href = '/articles';
                });
            },
            error: $.alert.ajaxError
        });
    }
});

$("#file-upload-btn").click(function () {
    $.modal.material.open({multiSelect: false}, function (selectedImageUrl) {
        $("#cover-img-input").val(selectedImageUrl);
        $(".preview img.coverImage").attr("src", selectedImageUrl);
    })
});

// 选择图片
$("#file-btn").click(function () {
    var $this = $(this);
    $("#cover-img-file").click();
});
$("#input-material-upload").uploadPreview({imgContainer: ".preview", width: 190, height: 200});

